package com.ruoyi.plus.config;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.utils.SecurityUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.util.Date;

/**
 * 处理新增和更新的基础数据填充，配合BaseEntity和MyBatisPlusConfig使用
 */
@Component
@Slf4j
public class AutoFillMetaObjectHandler implements MetaObjectHandler {

    /**
     * 新增数据执行
     *
     * @param metaObject
     */
    @Override
    public void insertFill(MetaObject metaObject) {
        LoginUser userEntity = null;
        try {
            userEntity = SecurityUtils.getLoginUser();
        } catch (Exception e) {
            //logger.error("获取shiro用户失败", e);
        }

        if (userEntity != null && userEntity.getUser() != null) {
            Long userId = userEntity.getUser().getUserId();
            String nickName = userEntity.getUser().getNickName();
            this.setFieldValByName("createId", userId, metaObject);
            this.setFieldValByName("createBy", nickName, metaObject);
            this.setFieldValByName("updateId", userId, metaObject);
            this.setFieldValByName("updateBy", nickName, metaObject);
        }
        this.setFieldValByName("createTime", new Date(), metaObject);
        this.setFieldValByName("updateTime", new Date(), metaObject);
        //this.setFieldValByName("tenantId",ShiroUtils.getTenantId(),metaObject);
    }

    /**
     * 更新数据执行
     *
     * @param metaObject
     */
    @Override
    public void updateFill(MetaObject metaObject) {
        LoginUser userEntity = null;
        try {
            userEntity = SecurityUtils.getLoginUser();
        } catch (Exception e) {
            //logger.error("获取shiro用户失败", e);
        }
        this.setFieldValByName("updateTime", new Date(), metaObject);
        if (userEntity != null && userEntity.getUser() != null) {
            this.setFieldValByName("updateId", userEntity.getUser().getUserId(), metaObject);
            this.setFieldValByName("updateBy", userEntity.getUser().getNickName(), metaObject);
        }
    }

}
